#include <iostream>
#include <signal.h>
#include "../comm/httplib.h"
#include "oj_controller.hpp"

using namespace httplib;
using namespace ns_controller;

Controller* pctrl = nullptr;

void Handler(int signo)
{
    pctrl->OnlineMachines();
}

int main()
{
    signal(SIGQUIT, Handler);
    Server svr;
    Controller ctrl;
    // std::cout << "创建svr和ctrl成功" << std::endl;
    pctrl = &ctrl;

    // 获取所有题目的信息
    svr.Get("/all_questions", [&ctrl](const Request& req, Response& resp){
        std::string html;
        ctrl.AllQuestions(&html);
        resp.set_content(html, "text/html;charset=utf8");
        // resp.set_content("全部题目信息", "text/plain;charset=utf8");
    });

    // 获取单个题目详细信息
    // /question/(\d+) -- 正则匹配，\d为数字，eg. /question/100
    // R"()" -- C++ 新特性，保留原始字符串
    svr.Get(R"(/question/(\d+))", [&ctrl](const Request& req, Response& resp){
        // std::string test = req.matches[0];
        std::string number = req.matches[1];
        std::string html;
        ctrl.OneQuestion(number, &html);
        resp.set_content(html, "text/html;charset=utf8");
        // resp.set_content("这是详细题目信息：" + number + " " + test, "text/plain;charset=utf8");
    });

    // 调用判题功能
    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request& req, Response& resp){
        std::string number = req.matches[1];
        // resp.set_content("这是指定题目的判题：" + number, "text/plain;charset=utf8");
        std::string out_json;
        ctrl.Judge(number, req.body, &out_json);
        resp.set_content(out_json, "application/json, charset=utf8");
    });
    svr.set_base_dir("./wwwroot");

    svr.listen("0.0.0.0", 8080);
    return 0;
}